package com.lalosoft.misgastos.service;

import java.sql.SQLException;
import java.util.Calendar;
import java.util.List;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import com.lalosoft.misgastos.activities.ItemListActivity;
import com.lalosoft.misgastos.config.Constants;
import com.lalosoft.misgastos.config.GastosManager;
import com.lalosoft.misgastos.config.Utils;
import com.lalosoft.misgastos.domain.Item;
import com.lalosoft.misgastos.receiver.GastosReceiver;

public class RecalculateService extends Service {
	
	private static String TAG = "RecalculateService";

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		try{
			Log.i(TAG, "Inicia el servicio de recalcular");
			if(recalculateItems()){
				Log.d(TAG, "Hay gastos para este mes");
				schedule();
				boolean avisos = GastosManager.getInstance(getApplicationContext()).avisosMensualesActivado(); 
				if(avisos){
//					if(Utils.checkNetwork(getApplicationContext()).equals("OK")){
//						sendEmail();	
//					}
					Intent action = new Intent(getApplicationContext(), ItemListActivity.class);
					Utils.showNotification(getApplicationContext(),Constants.NOTIFICATION_TICKER,
											Constants.NOTIFICATION_TITLE, 
											Constants.NOTIFICATION_TEXT, 
											action);
				}
				GastosManager.getInstance(getApplicationContext()).setLastRecalculate(System.currentTimeMillis());
			} else {
				GastosManager.getInstance(getApplicationContext()).setFirstTime(true);
			}
		} catch (Exception e){
			Log.e(TAG, "Error : " + e.getMessage());
		}
		
	}
	
//	private void sendEmail() throws Exception{
//		EmailSenderManager senderManager = EmailSenderManager.getInstance(getApplicationContext());
//		senderManager.sendEmail();
//	}

	private void schedule() {
		// get a Calendar object with current time
		Calendar cal = Calendar.getInstance();
//		cal.add(Calendar.DAY_OF_MONTH, 1);
		cal.add(Calendar.MINUTE, 3);
		Intent intent = new Intent(getApplicationContext(), GastosReceiver.class);
		intent.putExtra(Constants.EXTRA_ALARM_MESSAGE, Constants.EXTRA_ALARM_MESSAGE_ACTION);

		PendingIntent sender = PendingIntent.getBroadcast(this, Constants.REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);

		// Get the AlarmManager service
		AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
		am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);
	}

	private boolean recalculateItems() {
		List<Item> list = null;
		boolean hayGastos = false;
		GastosManager manager = GastosManager.getInstance(getApplicationContext());
		try {
			list = manager.getAllItems();
			if(list.size() > 0){
				for(Item temp : list){
					int restantes = temp.getCuotasRestantes();
					restantes--;
					Log.i(TAG, "Cuotas restantes actualizado : " + restantes);
					if(restantes > 0){
						temp.setCuotasRestantes(restantes);
						manager.updateItem(temp);
					} else {
						manager.deleteItem(temp);
						Log.d(TAG, "Item: " + temp.getDetalle());
						Log.d(TAG, "Se elimino el item porque no hay mas cuotas");
					}
				}
			}
			hayGastos = manager.getAllItems().size() > 0;
			
		} catch (SQLException e) {
			Log.e(TAG, "Error en DB" + e.getMessage());
		}
		Log.d(TAG, "Has Gastos: " + hayGastos);
		return hayGastos;
	}

}
